<?php
//require_once  __DIR__ . '/includes/authenticate.php';

if (isset($_POST['username']) && isset($_POST['firstname']) && isset($_POST['lastname']) &&  isset($_POST['pwd'])&& isset($_POST['pwdconfirm'])) {

require_once __DIR__ . '/db_connect_basketbal.php';


$username = $_POST['username'];
$firstname = ucfirst($_POST['firstname']);
$lastname = ucfirst($_POST['lastname']);
$pwd = $_POST['pwd'];
$pwdconfirm = $_POST['pwdconfirm'];

// check if password are equal
if ($pwd != $pwdconfirm) {
	echo "Passwords do not match"; 
} else {
	// check if username already exists
	$sql = "SELECT COUNT(*) FROM users WHERE username = :username";
	$stmt = $db->prepare($sql);
	$stmt->bindParam(':username', $username);
	$stmt->execute();
	if ($stmt->fetchColumn() != 0) {
		echo "$username already in use, Choose another username.";
	} else {
		try {	
				//Create new user in DB
				$user_key = hash('crc32', microtime(true). mt_rand().$username);
				$sql = "INSERT INTO users (user_key, username, pwd, firstname, lastname) VALUES (:key,:username,:pwd, :firstname, :lastname)";
				$stmt = $db->prepare($sql);
				$stmt->bindParam(':key', $user_key);
				$stmt->bindParam(':username', $username);
				$stmt->bindValue(':pwd', password_hash($pwd, PASSWORD_DEFAULT));
				$stmt->bindParam(':firstname', $firstname);
				$stmt->bindParam(':lastname', $lastname);
				$stmt->execute();
				} catch (\PDOException $e){
					if (0 === strpos($e->getCode(),'23')) {
						$user_key = hash('crc32', microtime(true). mt_rand().$username);
						if (!$stmt->execute()) {
							throw $e;
						}
					}
				}
				if ($stmt->rowCount()) {
					echo "User $firstname $lastname successfully added";
					//header('Location: login.php');
					exit;
				}
		}
	}
}// close if isset post

?>

